package com.sunyy.codegenerator.config;

import com.sunyy.codegenerator.common.Message;
import com.sunyy.codegenerator.common.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {Throwable.class})
    public ResponseEntity<Message<Object>> handleAllExceptions(Throwable e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(Message.error("系统异常!!!"), HttpStatus.OK);  // 不能失败的状态码，会被网关拦截
    }

    @ExceptionHandler(value = {MyException.class})
    public ResponseEntity<Message<Object>> handleMyExceptions(MyException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(Message.error(e.getMessage()), HttpStatus.OK);
    }

    @ExceptionHandler(value = {IllegalArgumentException.class})
    public ResponseEntity<Message<Object>> handleIllegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(Message.error(e.getMessage()), HttpStatus.OK);
    }
}
